import 'package:flutter/material.dart';
import 'package:flutterapp/src/utils/log_utils.dart';

main() {
  runApp(
    MaterialApp(
      home: ScrollIndexpage(),
    ),
  );
}

class ScrollIndexpage extends StatefulWidget {
  @override
  _ScrollIndexpageState createState() => _ScrollIndexpageState();
}

class _ScrollIndexpageState extends State<ScrollIndexpage> {
  // 当前选中的item
  int _currentSelectIndex = 0;
  double _itemWidth = 0.0;
  // 滑动控制器
  ScrollController _scrollController = new ScrollController();
  @override
  void initState() {
    super.initState();
    // 滑动过程中也实时刷新
    _scrollController.addListener(() {
      setState(() {});
    });
  }

  @override
  Widget build(BuildContext context) {
    setState(() {
      _itemWidth = MediaQuery.of(context).size.width / 5;
    });
    // 第一步 列表显示出来
    // 第二步 列表自动滑动
    // 第三部 中间放大显示
    // 第四步 动态放大与缩小
    return Scaffold(
      appBar: AppBar(
        title: Text("List-demo"),
      ),
      body: Container(
        width: double.infinity,
        height: double.infinity,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text("当前选中 $_currentSelectIndex"),
            Container(
              height: 300,
              child: buildSingleChildScrollview(),
            ),
            Icon(Icons.arrow_forward_outlined),
          ],
        ),
      ),
    );
  }

  buildSingleChildScrollview() {
    return NotificationListener<ScrollEndNotification>(
      onNotification: (ScrollNotification scrollNotification) {
        // 滑动信息封装
        ScrollMetrics metrics = scrollNotification.metrics;
        // 获取当前滑动的位置
        double pixels = metrics.pixels;
        // 最大的滑动距离
        double maxScrollExtent = metrics.maxScrollExtent;
        // 计算滑动位置
        double scrollIndex = pixels / _itemWidth;
        double scrollOffset = pixels % _itemWidth;
        // 当前选中 四舍五入
        _currentSelectIndex = scrollIndex.round();
        if (pixels == maxScrollExtent) {
          LogUtils.e("已经滑动到了底部");
        } else if (pixels == 0) {
          LogUtils.e("已经滑动到了顶部");
        } else {
          if (scrollOffset != 0.0) {
            LogUtils.e("滑动结束，未滑动到边界 scrollIndex $scrollIndex");
            Future.delayed(Duration.zero, () {
              _scrollController.animateTo(_currentSelectIndex * _itemWidth,
                  duration: Duration(milliseconds: 200), curve: Curves.linear);
            });
          } else {
            LogUtils.e("滑动结束，滑动到边界 scrollIndex $scrollIndex");
          }
        }
        // 更新视图
        setState(() {});
        return true;
      },
      child: SingleChildScrollView(
        controller: _scrollController,
        scrollDirection: Axis.horizontal,
        child: Row(
          children: buildChildren(),
        ),
      ),
    );
  }

  buildChildren() {
    List<Widget> list = [];
    for (int i = 0; i < 20; i++) {
      list.add(buildItemWidget(i));
    }
    return list;
  }

  Widget buildItemWidget(int index) {
    Color textColor = Colors.grey;
    double fontSize = 14;
    double imageWidth = 55.0;
    double opacity = 1;
    if (index == 0 || index == 1 || index == 19 || index == 18) {
      opacity = 0;
    }
    // 当控制器绑定成功后使用
    if (_scrollController.hasClients) {
      // 获取当前的活动距离
      double offset = _scrollController.offset;
      double scrollIndex = offset / _itemWidth;
      double uniWidth = scrollIndex - scrollIndex.round();
      LogUtils.e("uniWidth $uniWidth  ${scrollIndex.round()}");
      if ((scrollIndex.round() + 2) == index) {
        textColor = Colors.redAccent;
        fontSize = 16;
        imageWidth = 55.0 + 20 * (1.0 - uniWidth);
      } else if ((scrollIndex.round() + 3) == index ||
          (scrollIndex.round() + 1) == index) {
        imageWidth = 55.0 + 20 * uniWidth;
      }
    }
    return Opacity(
      opacity: opacity,
      child: Container(
        width: _itemWidth,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            //裁剪圆形
            ClipOval(
              child: Image.asset(
                "assets/images/app_icon.png",
                width: imageWidth,
                height: imageWidth,
                fit: BoxFit.fill,
              ),
            ),
            //图片
            //文字
            Text(
              "测试$index",
              style: TextStyle(
                color: textColor,
                fontSize: fontSize,
              ),
            ),
          ],
        ),
      ),
    );
  }
}
